{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "provenance": [],
      "include_colab_link": true
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "view-in-github",
        "colab_type": "text"
      },
      "source": [
        "<a href=\"https://colab.research.google.com/github/nceder/qpb4e/blob/main/code/Chapter%2010/Chapter_10.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "# 10 Modules and scoping rules\n",
        "\n",
        "# 10.2 A first module"
      ],
      "metadata": {
        "id": "C-jdZSY2Rc-y"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "%%writefile mymath.py\n",
        "\"\"\"mymath - our example math module\"\"\"\n",
        "pi = 3.14159\n",
        "def area(r):\n",
        "    \"\"\"area(r): return the area of a circle with radius r.\"\"\"\n",
        "    return(pi * r * r)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "eC41JX_SQJmG",
        "outputId": "fe086d2d-de83-404b-da85-4e7d33ed6d2a"
      },
      "execution_count": 10,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Writing mymath.py\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "jRgUz_qjQIHb",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 141
        },
        "outputId": "ea2d0468-a949-436d-ff8a-e13d3e487060"
      },
      "source": [
        "pi"
      ],
      "execution_count": 11,
      "outputs": [
        {
          "output_type": "error",
          "ename": "NameError",
          "evalue": "name 'pi' is not defined",
          "traceback": [
            "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
            "\u001b[0;31mNameError\u001b[0m                                 Traceback (most recent call last)",
            "\u001b[0;32m<ipython-input-11-f84ab820532c>\u001b[0m in \u001b[0;36m<cell line: 1>\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mpi\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
            "\u001b[0;31mNameError\u001b[0m: name 'pi' is not defined"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "uvMejn7eQIHd",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 141
        },
        "outputId": "54a7bd36-fc6b-4077-988b-b8af56ea2a24"
      },
      "source": [
        "area(2)"
      ],
      "execution_count": 12,
      "outputs": [
        {
          "output_type": "error",
          "ename": "NameError",
          "evalue": "name 'area' is not defined",
          "traceback": [
            "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
            "\u001b[0;31mNameError\u001b[0m                                 Traceback (most recent call last)",
            "\u001b[0;32m<ipython-input-12-8be925061d22>\u001b[0m in \u001b[0;36m<cell line: 1>\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0marea\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m2\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
            "\u001b[0;31mNameError\u001b[0m: name 'area' is not defined"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "VIS-iqkKQIHe",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 159
        },
        "outputId": "612be8fe-15b1-4387-a139-8bf525bf86ad"
      },
      "source": [
        "import mymath\n",
        "pi"
      ],
      "execution_count": 14,
      "outputs": [
        {
          "output_type": "error",
          "ename": "NameError",
          "evalue": "name 'pi' is not defined",
          "traceback": [
            "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
            "\u001b[0;31mNameError\u001b[0m                                 Traceback (most recent call last)",
            "\u001b[0;32m<ipython-input-14-85b32257cf04>\u001b[0m in \u001b[0;36m<cell line: 2>\u001b[0;34m()\u001b[0m\n\u001b[1;32m      1\u001b[0m \u001b[0;32mimport\u001b[0m \u001b[0mmymath\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0mpi\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
            "\u001b[0;31mNameError\u001b[0m: name 'pi' is not defined"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "12y-aTDMQIHe",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "f5ebe5eb-0975-4f52-c043-573e109b14c4"
      },
      "source": [
        "mymath.pi"
      ],
      "execution_count": 15,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "3.14159"
            ]
          },
          "metadata": {},
          "execution_count": 15
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "ylXhBIlSQIHf",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "d53b0ec8-9da4-4adc-a7ac-e59b74dfff50"
      },
      "source": [
        "mymath.area(2)"
      ],
      "execution_count": 16,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "12.56636"
            ]
          },
          "metadata": {},
          "execution_count": 16
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "YMOolAmLQIHf",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 35
        },
        "outputId": "b05e848a-1562-42e3-a2a1-87c4da96b222"
      },
      "source": [
        "mymath.__doc__"
      ],
      "execution_count": 17,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "'mymath - our example math module'"
            ],
            "application/vnd.google.colaboratory.intrinsic+json": {
              "type": "string"
            }
          },
          "metadata": {},
          "execution_count": 17
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "fBUR1Z_bQIHf",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 35
        },
        "outputId": "18d5f72f-d0d6-43be-b73a-8fa531045458"
      },
      "source": [
        "mymath.area.__doc__"
      ],
      "execution_count": 18,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "'area(r): return the area of a circle with radius r.'"
            ],
            "application/vnd.google.colaboratory.intrinsic+json": {
              "type": "string"
            }
          },
          "metadata": {},
          "execution_count": 18
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "D2TT6OdjQIHg",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "b7438057-fbf6-4bdd-ba15-a63758d34913"
      },
      "source": [
        "from mymath import pi\n",
        "pi"
      ],
      "execution_count": 19,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "3.14159"
            ]
          },
          "metadata": {},
          "execution_count": 19
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "DtlNqMAFQIHg",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 141
        },
        "outputId": "df378f5b-4b65-4d17-8d7e-bb59c2b40529"
      },
      "source": [
        "area(2)"
      ],
      "execution_count": 20,
      "outputs": [
        {
          "output_type": "error",
          "ename": "NameError",
          "evalue": "name 'area' is not defined",
          "traceback": [
            "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
            "\u001b[0;31mNameError\u001b[0m                                 Traceback (most recent call last)",
            "\u001b[0;32m<ipython-input-20-8be925061d22>\u001b[0m in \u001b[0;36m<cell line: 1>\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0marea\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m2\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
            "\u001b[0;31mNameError\u001b[0m: name 'area' is not defined"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "MTMSTiCrQIHh",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "713bfa1a-8ef7-4ec0-909e-88ba1f0fa213"
      },
      "source": [
        "import mymath, importlib\n",
        "importlib.reload(mymath)"
      ],
      "execution_count": 21,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "<module 'mymath' from '/content/mymath.py'>"
            ]
          },
          "metadata": {},
          "execution_count": 21
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "# 10.3 The import statement"
      ],
      "metadata": {
        "id": "cxapg7m5kVpi"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "from mymath import *"
      ],
      "metadata": {
        "id": "800bZp6AkcVV"
      },
      "execution_count": 22,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "# 10.4 The module search path"
      ],
      "metadata": {
        "id": "ejwLhgI0SBhi"
      }
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "C8p-QRLuQIHh",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "1e695ef3-4691-40fe-82cf-afb08609b5e8"
      },
      "source": [
        "import sys\n",
        "sys.path"
      ],
      "execution_count": 23,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "['/content',\n",
              " '/env/python',\n",
              " '/usr/lib/python310.zip',\n",
              " '/usr/lib/python3.10',\n",
              " '/usr/lib/python3.10/lib-dynload',\n",
              " '',\n",
              " '/usr/local/lib/python3.10/dist-packages',\n",
              " '/usr/lib/python3/dist-packages',\n",
              " '/usr/local/lib/python3.10/dist-packages/IPython/extensions',\n",
              " '/usr/local/lib/python3.10/dist-packages/setuptools/_vendor',\n",
              " '/root/.ipython']"
            ]
          },
          "metadata": {},
          "execution_count": 23
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "# 10.5 Private names in modules"
      ],
      "metadata": {
        "id": "8jJwr8D0SwXX"
      }
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "9fyASMnvQIHi",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "23cda395-22d6-4636-f864-0fd1b493254f"
      },
      "source": [
        "%%writefile modtest.py(\n",
        "\"\"\"modtest: our test module\"\"\"\n",
        "def f(x):\n",
        "    return x\n",
        "def _g(x):\n",
        "    return x\n",
        "a = 4\n",
        "_b = 2"
      ],
      "execution_count": 25,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Writing modtest.py(\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "wAYZJv3oQIHi",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "9d9f049b-323b-4abb-8371-fd6502446b28"
      },
      "source": [
        "from modtest import *\n",
        "f(3)"
      ],
      "execution_count": 26,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "3"
            ]
          },
          "metadata": {},
          "execution_count": 26
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "cfw30CZXQIHi",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 141
        },
        "outputId": "33bb5539-76ba-4f80-ef93-46adeed18a47"
      },
      "source": [
        "_g(3)"
      ],
      "execution_count": 27,
      "outputs": [
        {
          "output_type": "error",
          "ename": "NameError",
          "evalue": "name '_g' is not defined",
          "traceback": [
            "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
            "\u001b[0;31mNameError\u001b[0m                                 Traceback (most recent call last)",
            "\u001b[0;32m<ipython-input-27-787abdf7161a>\u001b[0m in \u001b[0;36m<cell line: 1>\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0m_g\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m3\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
            "\u001b[0;31mNameError\u001b[0m: name '_g' is not defined"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "xqNHiSibQIHi",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "f3fd86c9-063f-4925-ae6f-cd3640e3fea4"
      },
      "source": [
        "a"
      ],
      "execution_count": 28,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "4"
            ]
          },
          "metadata": {},
          "execution_count": 28
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "pHSASbQZQIHj",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 141
        },
        "outputId": "6d497652-5697-4b6a-c710-00c836a65d86"
      },
      "source": [
        "_b"
      ],
      "execution_count": 29,
      "outputs": [
        {
          "output_type": "error",
          "ename": "NameError",
          "evalue": "name '_b' is not defined",
          "traceback": [
            "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
            "\u001b[0;31mNameError\u001b[0m                                 Traceback (most recent call last)",
            "\u001b[0;32m<ipython-input-29-8352e74fe22a>\u001b[0m in \u001b[0;36m<cell line: 1>\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0m_b\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
            "\u001b[0;31mNameError\u001b[0m: name '_b' is not defined"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "5DrFissvQIHj",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "abc4b771-4fb0-41e5-b8a2-6ca35a384c3d"
      },
      "source": [
        "import modtest\n",
        "modtest._b"
      ],
      "execution_count": 30,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "2"
            ]
          },
          "metadata": {},
          "execution_count": 30
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "Ekeax76XQIHj",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "6db71f7f-0b1e-4a86-e3ff-e68aac0293fd"
      },
      "source": [
        "from modtest import _g\n",
        "_g(5)"
      ],
      "execution_count": 31,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "5"
            ]
          },
          "metadata": {},
          "execution_count": 31
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "# 10.6 Library and third-party modules"
      ],
      "metadata": {
        "id": "HUz6HBVaT15p"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "### Quick Check: Modules\n",
        "Suppose that you have a module called `new_math` that contains a function called `new_divide`. What are the ways that you might import and then use that function? What are the pros and cons of each method?\n",
        "\n",
        "```python\n",
        "import new_math\n",
        "new_math.new_divide(...)\n",
        "```\n",
        "**This solution is often preferred because there won’t be a clash between any identifiers in new_module and the importing namespace. This solution is less convenient to type, however.**\n",
        "\n",
        "```python\n",
        "from new_math import new_divide\n",
        "new_divide(...)\n",
        "```\n",
        "**This version is more convenient to use but increases the chance of name clashes between identifiers in the module and the importing namespace.**\n",
        "\n",
        "Suppose that the new_math module contains a function called `_helper_mat-h()`. How will the underscore character affect the way that `_helper_math()` is imported?\n",
        "\n",
        "**It won’t be imported if you use `from new_math import*`**\n"
      ],
      "metadata": {
        "id": "5BUEPpirT8JQ"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "# 10.7 Python scoping rules and namespaces"
      ],
      "metadata": {
        "id": "QroaWNq6UTuj"
      }
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "-dC1Qb1DQIHj",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "87f3b91d-08d9-4aa7-e043-adc1631ec8db"
      },
      "source": [
        "locals()"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "{'__name__': '__main__',\n",
              " '__doc__': 'Automatically created module for IPython interactive environment',\n",
              " '__package__': None,\n",
              " '__loader__': None,\n",
              " '__spec__': None,\n",
              " '__builtin__': <module 'builtins' (built-in)>,\n",
              " '__builtins__': <module 'builtins' (built-in)>,\n",
              " '_ih': ['',\n",
              "  'open(\"mymath.py\", \"w\").write(\\n\\'\\'\\'\"\"\"mymath - our example math module\"\"\"\\npi = 3.14159\\ndef area(r):\\n    \"\"\"area(r): return the area of a circle with radius r.\"\"\"\\n    return(pi * r * r) \\n\\'\\'\\')',\n",
              "  'import mymath\\npi',\n",
              "  'mymath.pi',\n",
              "  'mymath.area(2)',\n",
              "  'mymath.pi',\n",
              "  'mymath.area(2)',\n",
              "  'mymath.__doc__',\n",
              "  'mymath.area.__doc__',\n",
              "  'from mymath import pi\\npi',\n",
              "  'area(2)',\n",
              "  'import mymath, importlib\\nimportlib.reload(mymath)',\n",
              "  'import sys\\nsys.path',\n",
              "  'open(\"modtest.py\", \"w\").write(\\n\\'\\'\\'\"\"\"modtest: our test module\"\"\"\\ndef f(x):\\n    return x\\ndef _g(x):\\n    return x\\na = 4\\n_b = 2\\n\\'\\'\\')',\n",
              "  'from modtest import *\\nf(3)',\n",
              "  '_g(3)',\n",
              "  'a',\n",
              "  '_b',\n",
              "  'import modtest\\nmodtest._b',\n",
              "  'from modtest import _g\\n_g(5)',\n",
              "  'locals()'],\n",
              " '_oh': {1: 151,\n",
              "  3: 3.14159,\n",
              "  4: 12.56636,\n",
              "  5: 3.14159,\n",
              "  6: 12.56636,\n",
              "  7: 'mymath - our example math module',\n",
              "  8: 'area(r): return the area of a circle with radius r.',\n",
              "  9: 3.14159,\n",
              "  11: <module 'mymath' from '/content/mymath.py'>,\n",
              "  12: ['/content',\n",
              "   '/env/python',\n",
              "   '/usr/lib/python310.zip',\n",
              "   '/usr/lib/python3.10',\n",
              "   '/usr/lib/python3.10/lib-dynload',\n",
              "   '',\n",
              "   '/usr/local/lib/python3.10/dist-packages',\n",
              "   '/usr/lib/python3/dist-packages',\n",
              "   '/usr/local/lib/python3.10/dist-packages/IPython/extensions',\n",
              "   '/root/.ipython'],\n",
              "  13: 91,\n",
              "  14: 3,\n",
              "  16: 4,\n",
              "  18: 2,\n",
              "  19: 5},\n",
              " '_dh': ['/content'],\n",
              " 'In': ['',\n",
              "  'open(\"mymath.py\", \"w\").write(\\n\\'\\'\\'\"\"\"mymath - our example math module\"\"\"\\npi = 3.14159\\ndef area(r):\\n    \"\"\"area(r): return the area of a circle with radius r.\"\"\"\\n    return(pi * r * r) \\n\\'\\'\\')',\n",
              "  'import mymath\\npi',\n",
              "  'mymath.pi',\n",
              "  'mymath.area(2)',\n",
              "  'mymath.pi',\n",
              "  'mymath.area(2)',\n",
              "  'mymath.__doc__',\n",
              "  'mymath.area.__doc__',\n",
              "  'from mymath import pi\\npi',\n",
              "  'area(2)',\n",
              "  'import mymath, importlib\\nimportlib.reload(mymath)',\n",
              "  'import sys\\nsys.path',\n",
              "  'open(\"modtest.py\", \"w\").write(\\n\\'\\'\\'\"\"\"modtest: our test module\"\"\"\\ndef f(x):\\n    return x\\ndef _g(x):\\n    return x\\na = 4\\n_b = 2\\n\\'\\'\\')',\n",
              "  'from modtest import *\\nf(3)',\n",
              "  '_g(3)',\n",
              "  'a',\n",
              "  '_b',\n",
              "  'import modtest\\nmodtest._b',\n",
              "  'from modtest import _g\\n_g(5)',\n",
              "  'locals()'],\n",
              " 'Out': {1: 151,\n",
              "  3: 3.14159,\n",
              "  4: 12.56636,\n",
              "  5: 3.14159,\n",
              "  6: 12.56636,\n",
              "  7: 'mymath - our example math module',\n",
              "  8: 'area(r): return the area of a circle with radius r.',\n",
              "  9: 3.14159,\n",
              "  11: <module 'mymath' from '/content/mymath.py'>,\n",
              "  12: ['/content',\n",
              "   '/env/python',\n",
              "   '/usr/lib/python310.zip',\n",
              "   '/usr/lib/python3.10',\n",
              "   '/usr/lib/python3.10/lib-dynload',\n",
              "   '',\n",
              "   '/usr/local/lib/python3.10/dist-packages',\n",
              "   '/usr/lib/python3/dist-packages',\n",
              "   '/usr/local/lib/python3.10/dist-packages/IPython/extensions',\n",
              "   '/root/.ipython'],\n",
              "  13: 91,\n",
              "  14: 3,\n",
              "  16: 4,\n",
              "  18: 2,\n",
              "  19: 5},\n",
              " 'get_ipython': <bound method InteractiveShell.get_ipython of <google.colab._shell.Shell object at 0x79621d7d78b0>>,\n",
              " 'exit': <IPython.core.autocall.ZMQExitAutocall at 0x79621d7d7e50>,\n",
              " 'quit': <IPython.core.autocall.ZMQExitAutocall at 0x79621d7d7e50>,\n",
              " '_': 5,\n",
              " '__': 2,\n",
              " '___': 4,\n",
              " '_i': 'from modtest import _g\\n_g(5)',\n",
              " '_ii': 'import modtest\\nmodtest._b',\n",
              " '_iii': '_b',\n",
              " '_i1': 'open(\"mymath.py\", \"w\").write(\\n\\'\\'\\'\"\"\"mymath - our example math module\"\"\"\\npi = 3.14159\\ndef area(r):\\n    \"\"\"area(r): return the area of a circle with radius r.\"\"\"\\n    return(pi * r * r) \\n\\'\\'\\')',\n",
              " '_1': 151,\n",
              " '_i2': 'import mymath\\npi',\n",
              " 'mymath': <module 'mymath' from '/content/mymath.py'>,\n",
              " '_i3': 'mymath.pi',\n",
              " '_3': 3.14159,\n",
              " '_i4': 'mymath.area(2)',\n",
              " '_4': 12.56636,\n",
              " '_i5': 'mymath.pi',\n",
              " '_5': 3.14159,\n",
              " '_i6': 'mymath.area(2)',\n",
              " '_6': 12.56636,\n",
              " '_i7': 'mymath.__doc__',\n",
              " '_7': 'mymath - our example math module',\n",
              " '_i8': 'mymath.area.__doc__',\n",
              " '_8': 'area(r): return the area of a circle with radius r.',\n",
              " '_i9': 'from mymath import pi\\npi',\n",
              " 'pi': 3.14159,\n",
              " '_9': 3.14159,\n",
              " '_i10': 'area(2)',\n",
              " '_i11': 'import mymath, importlib\\nimportlib.reload(mymath)',\n",
              " 'importlib': <module 'importlib' from '/usr/lib/python3.10/importlib/__init__.py'>,\n",
              " '_11': <module 'mymath' from '/content/mymath.py'>,\n",
              " '_i12': 'import sys\\nsys.path',\n",
              " 'sys': <module 'sys' (built-in)>,\n",
              " '_12': ['/content',\n",
              "  '/env/python',\n",
              "  '/usr/lib/python310.zip',\n",
              "  '/usr/lib/python3.10',\n",
              "  '/usr/lib/python3.10/lib-dynload',\n",
              "  '',\n",
              "  '/usr/local/lib/python3.10/dist-packages',\n",
              "  '/usr/lib/python3/dist-packages',\n",
              "  '/usr/local/lib/python3.10/dist-packages/IPython/extensions',\n",
              "  '/root/.ipython'],\n",
              " '_i13': 'open(\"modtest.py\", \"w\").write(\\n\\'\\'\\'\"\"\"modtest: our test module\"\"\"\\ndef f(x):\\n    return x\\ndef _g(x):\\n    return x\\na = 4\\n_b = 2\\n\\'\\'\\')',\n",
              " '_13': 91,\n",
              " '_i14': 'from modtest import *\\nf(3)',\n",
              " 'f': <function modtest.f(x)>,\n",
              " 'a': 4,\n",
              " '_14': 3,\n",
              " '_i15': '_g(3)',\n",
              " '_i16': 'a',\n",
              " '_16': 4,\n",
              " '_i17': '_b',\n",
              " '_i18': 'import modtest\\nmodtest._b',\n",
              " 'modtest': <module 'modtest' from '/content/modtest.py'>,\n",
              " '_18': 2,\n",
              " '_i19': 'from modtest import _g\\n_g(5)',\n",
              " '_g': <function modtest._g(x)>,\n",
              " '_19': 5,\n",
              " '_i20': 'locals()'}"
            ]
          },
          "metadata": {},
          "execution_count": 20
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "Oy4MgtPzQIHk",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "fea58e23-33e2-47e9-b47f-419391524095"
      },
      "source": [
        "globals()"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "{'__name__': '__main__',\n",
              " '__doc__': 'Automatically created module for IPython interactive environment',\n",
              " '__package__': None,\n",
              " '__loader__': None,\n",
              " '__spec__': None,\n",
              " '__builtin__': <module 'builtins' (built-in)>,\n",
              " '__builtins__': <module 'builtins' (built-in)>,\n",
              " '_ih': ['',\n",
              "  'open(\"mymath.py\", \"w\").write(\\n\\'\\'\\'\"\"\"mymath - our example math module\"\"\"\\npi = 3.14159\\ndef area(r):\\n    \"\"\"area(r): return the area of a circle with radius r.\"\"\"\\n    return(pi * r * r) \\n\\'\\'\\')',\n",
              "  'import mymath\\npi',\n",
              "  'mymath.pi',\n",
              "  'mymath.area(2)',\n",
              "  'mymath.pi',\n",
              "  'mymath.area(2)',\n",
              "  'mymath.__doc__',\n",
              "  'mymath.area.__doc__',\n",
              "  'from mymath import pi\\npi',\n",
              "  'area(2)',\n",
              "  'import mymath, importlib\\nimportlib.reload(mymath)',\n",
              "  'import sys\\nsys.path',\n",
              "  'open(\"modtest.py\", \"w\").write(\\n\\'\\'\\'\"\"\"modtest: our test module\"\"\"\\ndef f(x):\\n    return x\\ndef _g(x):\\n    return x\\na = 4\\n_b = 2\\n\\'\\'\\')',\n",
              "  'from modtest import *\\nf(3)',\n",
              "  '_g(3)',\n",
              "  'a',\n",
              "  '_b',\n",
              "  'import modtest\\nmodtest._b',\n",
              "  'from modtest import _g\\n_g(5)',\n",
              "  'locals()',\n",
              "  'globals()'],\n",
              " '_oh': {1: 151,\n",
              "  3: 3.14159,\n",
              "  4: 12.56636,\n",
              "  5: 3.14159,\n",
              "  6: 12.56636,\n",
              "  7: 'mymath - our example math module',\n",
              "  8: 'area(r): return the area of a circle with radius r.',\n",
              "  9: 3.14159,\n",
              "  11: <module 'mymath' from '/content/mymath.py'>,\n",
              "  12: ['/content',\n",
              "   '/env/python',\n",
              "   '/usr/lib/python310.zip',\n",
              "   '/usr/lib/python3.10',\n",
              "   '/usr/lib/python3.10/lib-dynload',\n",
              "   '',\n",
              "   '/usr/local/lib/python3.10/dist-packages',\n",
              "   '/usr/lib/python3/dist-packages',\n",
              "   '/usr/local/lib/python3.10/dist-packages/IPython/extensions',\n",
              "   '/root/.ipython'],\n",
              "  13: 91,\n",
              "  14: 3,\n",
              "  16: 4,\n",
              "  18: 2,\n",
              "  19: 5,\n",
              "  20: {...}},\n",
              " '_dh': ['/content'],\n",
              " 'In': ['',\n",
              "  'open(\"mymath.py\", \"w\").write(\\n\\'\\'\\'\"\"\"mymath - our example math module\"\"\"\\npi = 3.14159\\ndef area(r):\\n    \"\"\"area(r): return the area of a circle with radius r.\"\"\"\\n    return(pi * r * r) \\n\\'\\'\\')',\n",
              "  'import mymath\\npi',\n",
              "  'mymath.pi',\n",
              "  'mymath.area(2)',\n",
              "  'mymath.pi',\n",
              "  'mymath.area(2)',\n",
              "  'mymath.__doc__',\n",
              "  'mymath.area.__doc__',\n",
              "  'from mymath import pi\\npi',\n",
              "  'area(2)',\n",
              "  'import mymath, importlib\\nimportlib.reload(mymath)',\n",
              "  'import sys\\nsys.path',\n",
              "  'open(\"modtest.py\", \"w\").write(\\n\\'\\'\\'\"\"\"modtest: our test module\"\"\"\\ndef f(x):\\n    return x\\ndef _g(x):\\n    return x\\na = 4\\n_b = 2\\n\\'\\'\\')',\n",
              "  'from modtest import *\\nf(3)',\n",
              "  '_g(3)',\n",
              "  'a',\n",
              "  '_b',\n",
              "  'import modtest\\nmodtest._b',\n",
              "  'from modtest import _g\\n_g(5)',\n",
              "  'locals()',\n",
              "  'globals()'],\n",
              " 'Out': {1: 151,\n",
              "  3: 3.14159,\n",
              "  4: 12.56636,\n",
              "  5: 3.14159,\n",
              "  6: 12.56636,\n",
              "  7: 'mymath - our example math module',\n",
              "  8: 'area(r): return the area of a circle with radius r.',\n",
              "  9: 3.14159,\n",
              "  11: <module 'mymath' from '/content/mymath.py'>,\n",
              "  12: ['/content',\n",
              "   '/env/python',\n",
              "   '/usr/lib/python310.zip',\n",
              "   '/usr/lib/python3.10',\n",
              "   '/usr/lib/python3.10/lib-dynload',\n",
              "   '',\n",
              "   '/usr/local/lib/python3.10/dist-packages',\n",
              "   '/usr/lib/python3/dist-packages',\n",
              "   '/usr/local/lib/python3.10/dist-packages/IPython/extensions',\n",
              "   '/root/.ipython'],\n",
              "  13: 91,\n",
              "  14: 3,\n",
              "  16: 4,\n",
              "  18: 2,\n",
              "  19: 5,\n",
              "  20: {...}},\n",
              " 'get_ipython': <bound method InteractiveShell.get_ipython of <google.colab._shell.Shell object at 0x79621d7d78b0>>,\n",
              " 'exit': <IPython.core.autocall.ZMQExitAutocall at 0x79621d7d7e50>,\n",
              " 'quit': <IPython.core.autocall.ZMQExitAutocall at 0x79621d7d7e50>,\n",
              " '_': {...},\n",
              " '__': 5,\n",
              " '___': 2,\n",
              " '_i': 'locals()',\n",
              " '_ii': 'from modtest import _g\\n_g(5)',\n",
              " '_iii': 'import modtest\\nmodtest._b',\n",
              " '_i1': 'open(\"mymath.py\", \"w\").write(\\n\\'\\'\\'\"\"\"mymath - our example math module\"\"\"\\npi = 3.14159\\ndef area(r):\\n    \"\"\"area(r): return the area of a circle with radius r.\"\"\"\\n    return(pi * r * r) \\n\\'\\'\\')',\n",
              " '_1': 151,\n",
              " '_i2': 'import mymath\\npi',\n",
              " 'mymath': <module 'mymath' from '/content/mymath.py'>,\n",
              " '_i3': 'mymath.pi',\n",
              " '_3': 3.14159,\n",
              " '_i4': 'mymath.area(2)',\n",
              " '_4': 12.56636,\n",
              " '_i5': 'mymath.pi',\n",
              " '_5': 3.14159,\n",
              " '_i6': 'mymath.area(2)',\n",
              " '_6': 12.56636,\n",
              " '_i7': 'mymath.__doc__',\n",
              " '_7': 'mymath - our example math module',\n",
              " '_i8': 'mymath.area.__doc__',\n",
              " '_8': 'area(r): return the area of a circle with radius r.',\n",
              " '_i9': 'from mymath import pi\\npi',\n",
              " 'pi': 3.14159,\n",
              " '_9': 3.14159,\n",
              " '_i10': 'area(2)',\n",
              " '_i11': 'import mymath, importlib\\nimportlib.reload(mymath)',\n",
              " 'importlib': <module 'importlib' from '/usr/lib/python3.10/importlib/__init__.py'>,\n",
              " '_11': <module 'mymath' from '/content/mymath.py'>,\n",
              " '_i12': 'import sys\\nsys.path',\n",
              " 'sys': <module 'sys' (built-in)>,\n",
              " '_12': ['/content',\n",
              "  '/env/python',\n",
              "  '/usr/lib/python310.zip',\n",
              "  '/usr/lib/python3.10',\n",
              "  '/usr/lib/python3.10/lib-dynload',\n",
              "  '',\n",
              "  '/usr/local/lib/python3.10/dist-packages',\n",
              "  '/usr/lib/python3/dist-packages',\n",
              "  '/usr/local/lib/python3.10/dist-packages/IPython/extensions',\n",
              "  '/root/.ipython'],\n",
              " '_i13': 'open(\"modtest.py\", \"w\").write(\\n\\'\\'\\'\"\"\"modtest: our test module\"\"\"\\ndef f(x):\\n    return x\\ndef _g(x):\\n    return x\\na = 4\\n_b = 2\\n\\'\\'\\')',\n",
              " '_13': 91,\n",
              " '_i14': 'from modtest import *\\nf(3)',\n",
              " 'f': <function modtest.f(x)>,\n",
              " 'a': 4,\n",
              " '_14': 3,\n",
              " '_i15': '_g(3)',\n",
              " '_i16': 'a',\n",
              " '_16': 4,\n",
              " '_i17': '_b',\n",
              " '_i18': 'import modtest\\nmodtest._b',\n",
              " 'modtest': <module 'modtest' from '/content/modtest.py'>,\n",
              " '_18': 2,\n",
              " '_i19': 'from modtest import _g\\n_g(5)',\n",
              " '_g': <function modtest._g(x)>,\n",
              " '_19': 5,\n",
              " '_i20': 'locals()',\n",
              " '_20': {...},\n",
              " '_i21': 'globals()'}"
            ]
          },
          "metadata": {},
          "execution_count": 21
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "HE3DRlVAQIHk",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "c84ee9a6-dcae-4de1-fc0e-d750616f2c02"
      },
      "source": [
        "z = 2\n",
        "import math\n",
        "from cmath import cos\n",
        "globals()"
      ],
      "execution_count": 36,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "{'__name__': '__main__',\n",
              " '__doc__': 'Automatically created module for IPython interactive environment',\n",
              " '__package__': None,\n",
              " '__loader__': None,\n",
              " '__spec__': None,\n",
              " '__builtin__': <module 'builtins' (built-in)>,\n",
              " '__builtins__': <module 'builtins' (built-in)>,\n",
              " '_ih': ['',\n",
              "  'get_ipython().run_cell_magic(\\'\\', \\'write mymath.py\\', \\'\"\"\"mymath - our example math module\"\"\"\\\\npi = 3.14159\\\\ndef area(r):\\\\n    \"\"\"area(r): return the area of a circle with radius r.\"\"\"\\\\n    return(pi * r * r)\\\\n\\')',\n",
              "  'get_ipython().run_cell_magic(\\'\\', \\'writefile mymath.py\\', \\'\"\"\"mymath - our example math module\"\"\"\\\\npi = 3.14159\\\\ndef area(r):\\\\n    \"\"\"area(r): return the area of a circle with radius r.\"\"\"\\\\n    return(pi * r * r)\\\\n\\')',\n",
              "  'pi',\n",
              "  'area(2)',\n",
              "  'import mymath\\npi',\n",
              "  'mymath.pi',\n",
              "  'mymath.area(2)',\n",
              "  'get_ipython().run_line_magic(\\'\\', \\'writefile mymath.py\\')\\n\"\"\"mymath - our example math module\"\"\"\\npi = 3.14159\\ndef area(r):\\n    \"\"\"area(r): return the area of a circle with radius r.\"\"\"\\n    return(pi * r * r)',\n",
              "  'get_ipython().run_line_magic(\\'writefile\\', \\'mymath.py\\')\\n\"\"\"mymath - our example math module\"\"\"\\npi = 3.14159\\ndef area(r):\\n    \"\"\"area(r): return the area of a circle with radius r.\"\"\"\\n    return(pi * r * r)',\n",
              "  'get_ipython().run_cell_magic(\\'writefile\\', \\'mymath.py\\', \\'\"\"\"mymath - our example math module\"\"\"\\\\npi = 3.14159\\\\ndef area(r):\\\\n    \"\"\"area(r): return the area of a circle with radius r.\"\"\"\\\\n    return(pi * r * r)\\\\n\\')',\n",
              "  'pi',\n",
              "  'area(2)',\n",
              "  'import mymath\\npi',\n",
              "  'import mymath\\npi',\n",
              "  'mymath.pi',\n",
              "  'mymath.area(2)',\n",
              "  'mymath.__doc__',\n",
              "  'mymath.area.__doc__',\n",
              "  'from mymath import pi\\npi',\n",
              "  'area(2)',\n",
              "  'import mymath, importlib\\nimportlib.reload(mymath)',\n",
              "  'from mymath import *',\n",
              "  'import sys\\nsys.path',\n",
              "  'open(\"modtest.py\", \"w\").write(\\n\\'\\'\\'\"\"\"modtest: our test module\"\"\"\\ndef f(x):\\n    return x\\ndef _g(x):\\n    return x\\na = 4\\n_b = 2\\n\\'\\'\\')',\n",
              "  'get_ipython().run_cell_magic(\\'writefile\\', \\'modtest.py(\\', \\'\"\"\"modtest: our test module\"\"\"\\\\ndef f(x):\\\\n    return x\\\\ndef _g(x):\\\\n    return x\\\\na = 4\\\\n_b = 2\\\\n\\')',\n",
              "  'from modtest import *\\nf(3)',\n",
              "  '_g(3)',\n",
              "  'a',\n",
              "  '_b',\n",
              "  'import modtest\\nmodtest._b',\n",
              "  'from modtest import _g\\n_g(5)',\n",
              "  'math.ceil(3.4)',\n",
              "  'import math\\nmath.ceil(3.4)',\n",
              "  'del z, math, cos',\n",
              "  'math.ceil(3.4)',\n",
              "  'z = 2\\nimport math\\nfrom cmath import cos\\nglobals()'],\n",
              " '_oh': {15: 3.14159,\n",
              "  16: 12.56636,\n",
              "  17: 'mymath - our example math module',\n",
              "  18: 'area(r): return the area of a circle with radius r.',\n",
              "  19: 3.14159,\n",
              "  21: <module 'mymath' from '/content/mymath.py'>,\n",
              "  23: ['/content',\n",
              "   '/env/python',\n",
              "   '/usr/lib/python310.zip',\n",
              "   '/usr/lib/python3.10',\n",
              "   '/usr/lib/python3.10/lib-dynload',\n",
              "   '',\n",
              "   '/usr/local/lib/python3.10/dist-packages',\n",
              "   '/usr/lib/python3/dist-packages',\n",
              "   '/usr/local/lib/python3.10/dist-packages/IPython/extensions',\n",
              "   '/usr/local/lib/python3.10/dist-packages/setuptools/_vendor',\n",
              "   '/root/.ipython'],\n",
              "  24: 91,\n",
              "  26: 3,\n",
              "  28: 4,\n",
              "  30: 2,\n",
              "  31: 5,\n",
              "  33: 4,\n",
              "  35: 4},\n",
              " '_dh': ['/content'],\n",
              " 'In': ['',\n",
              "  'get_ipython().run_cell_magic(\\'\\', \\'write mymath.py\\', \\'\"\"\"mymath - our example math module\"\"\"\\\\npi = 3.14159\\\\ndef area(r):\\\\n    \"\"\"area(r): return the area of a circle with radius r.\"\"\"\\\\n    return(pi * r * r)\\\\n\\')',\n",
              "  'get_ipython().run_cell_magic(\\'\\', \\'writefile mymath.py\\', \\'\"\"\"mymath - our example math module\"\"\"\\\\npi = 3.14159\\\\ndef area(r):\\\\n    \"\"\"area(r): return the area of a circle with radius r.\"\"\"\\\\n    return(pi * r * r)\\\\n\\')',\n",
              "  'pi',\n",
              "  'area(2)',\n",
              "  'import mymath\\npi',\n",
              "  'mymath.pi',\n",
              "  'mymath.area(2)',\n",
              "  'get_ipython().run_line_magic(\\'\\', \\'writefile mymath.py\\')\\n\"\"\"mymath - our example math module\"\"\"\\npi = 3.14159\\ndef area(r):\\n    \"\"\"area(r): return the area of a circle with radius r.\"\"\"\\n    return(pi * r * r)',\n",
              "  'get_ipython().run_line_magic(\\'writefile\\', \\'mymath.py\\')\\n\"\"\"mymath - our example math module\"\"\"\\npi = 3.14159\\ndef area(r):\\n    \"\"\"area(r): return the area of a circle with radius r.\"\"\"\\n    return(pi * r * r)',\n",
              "  'get_ipython().run_cell_magic(\\'writefile\\', \\'mymath.py\\', \\'\"\"\"mymath - our example math module\"\"\"\\\\npi = 3.14159\\\\ndef area(r):\\\\n    \"\"\"area(r): return the area of a circle with radius r.\"\"\"\\\\n    return(pi * r * r)\\\\n\\')',\n",
              "  'pi',\n",
              "  'area(2)',\n",
              "  'import mymath\\npi',\n",
              "  'import mymath\\npi',\n",
              "  'mymath.pi',\n",
              "  'mymath.area(2)',\n",
              "  'mymath.__doc__',\n",
              "  'mymath.area.__doc__',\n",
              "  'from mymath import pi\\npi',\n",
              "  'area(2)',\n",
              "  'import mymath, importlib\\nimportlib.reload(mymath)',\n",
              "  'from mymath import *',\n",
              "  'import sys\\nsys.path',\n",
              "  'open(\"modtest.py\", \"w\").write(\\n\\'\\'\\'\"\"\"modtest: our test module\"\"\"\\ndef f(x):\\n    return x\\ndef _g(x):\\n    return x\\na = 4\\n_b = 2\\n\\'\\'\\')',\n",
              "  'get_ipython().run_cell_magic(\\'writefile\\', \\'modtest.py(\\', \\'\"\"\"modtest: our test module\"\"\"\\\\ndef f(x):\\\\n    return x\\\\ndef _g(x):\\\\n    return x\\\\na = 4\\\\n_b = 2\\\\n\\')',\n",
              "  'from modtest import *\\nf(3)',\n",
              "  '_g(3)',\n",
              "  'a',\n",
              "  '_b',\n",
              "  'import modtest\\nmodtest._b',\n",
              "  'from modtest import _g\\n_g(5)',\n",
              "  'math.ceil(3.4)',\n",
              "  'import math\\nmath.ceil(3.4)',\n",
              "  'del z, math, cos',\n",
              "  'math.ceil(3.4)',\n",
              "  'z = 2\\nimport math\\nfrom cmath import cos\\nglobals()'],\n",
              " 'Out': {15: 3.14159,\n",
              "  16: 12.56636,\n",
              "  17: 'mymath - our example math module',\n",
              "  18: 'area(r): return the area of a circle with radius r.',\n",
              "  19: 3.14159,\n",
              "  21: <module 'mymath' from '/content/mymath.py'>,\n",
              "  23: ['/content',\n",
              "   '/env/python',\n",
              "   '/usr/lib/python310.zip',\n",
              "   '/usr/lib/python3.10',\n",
              "   '/usr/lib/python3.10/lib-dynload',\n",
              "   '',\n",
              "   '/usr/local/lib/python3.10/dist-packages',\n",
              "   '/usr/lib/python3/dist-packages',\n",
              "   '/usr/local/lib/python3.10/dist-packages/IPython/extensions',\n",
              "   '/usr/local/lib/python3.10/dist-packages/setuptools/_vendor',\n",
              "   '/root/.ipython'],\n",
              "  24: 91,\n",
              "  26: 3,\n",
              "  28: 4,\n",
              "  30: 2,\n",
              "  31: 5,\n",
              "  33: 4,\n",
              "  35: 4},\n",
              " 'get_ipython': <bound method InteractiveShell.get_ipython of <google.colab._shell.Shell object at 0x795e2e2321d0>>,\n",
              " 'exit': <IPython.core.autocall.ZMQExitAutocall at 0x795e2e232bc0>,\n",
              " 'quit': <IPython.core.autocall.ZMQExitAutocall at 0x795e2e232bc0>,\n",
              " '_': 4,\n",
              " '__': 4,\n",
              " '___': 5,\n",
              " '_i': 'math.ceil(3.4)',\n",
              " '_ii': 'del z, math, cos',\n",
              " '_iii': 'import math\\nmath.ceil(3.4)',\n",
              " '_i1': '%% write mymath.py\\n\"\"\"mymath - our example math module\"\"\"\\npi = 3.14159\\ndef area(r):\\n    \"\"\"area(r): return the area of a circle with radius r.\"\"\"\\n    return(pi * r * r)',\n",
              " '_i2': '%% writefile mymath.py\\n\"\"\"mymath - our example math module\"\"\"\\npi = 3.14159\\ndef area(r):\\n    \"\"\"area(r): return the area of a circle with radius r.\"\"\"\\n    return(pi * r * r)',\n",
              " '_i3': 'pi',\n",
              " '_i4': 'area(2)',\n",
              " '_i5': 'import mymath\\npi',\n",
              " '_i6': 'mymath.pi',\n",
              " '_i7': 'mymath.area(2)',\n",
              " '_i8': '% writefile mymath.py\\n\"\"\"mymath - our example math module\"\"\"\\npi = 3.14159\\ndef area(r):\\n    \"\"\"area(r): return the area of a circle with radius r.\"\"\"\\n    return(pi * r * r)',\n",
              " '_i9': '%writefile mymath.py\\n\"\"\"mymath - our example math module\"\"\"\\npi = 3.14159\\ndef area(r):\\n    \"\"\"area(r): return the area of a circle with radius r.\"\"\"\\n    return(pi * r * r)',\n",
              " '_i10': '%%writefile mymath.py\\n\"\"\"mymath - our example math module\"\"\"\\npi = 3.14159\\ndef area(r):\\n    \"\"\"area(r): return the area of a circle with radius r.\"\"\"\\n    return(pi * r * r)',\n",
              " '_i11': 'pi',\n",
              " '_i12': 'area(2)',\n",
              " '_i13': 'import mymath\\npi',\n",
              " 'mymath': <module 'mymath' from '/content/mymath.py'>,\n",
              " '_i14': 'import mymath\\npi',\n",
              " '_i15': 'mymath.pi',\n",
              " '_15': 3.14159,\n",
              " '_i16': 'mymath.area(2)',\n",
              " '_16': 12.56636,\n",
              " '_i17': 'mymath.__doc__',\n",
              " '_17': 'mymath - our example math module',\n",
              " '_i18': 'mymath.area.__doc__',\n",
              " '_18': 'area(r): return the area of a circle with radius r.',\n",
              " '_i19': 'from mymath import pi\\npi',\n",
              " 'pi': 3.14159,\n",
              " '_19': 3.14159,\n",
              " '_i20': 'area(2)',\n",
              " '_i21': 'import mymath, importlib\\nimportlib.reload(mymath)',\n",
              " 'importlib': <module 'importlib' from '/usr/lib/python3.10/importlib/__init__.py'>,\n",
              " '_21': <module 'mymath' from '/content/mymath.py'>,\n",
              " '_i22': 'from mymath import *',\n",
              " 'area': <function mymath.area(r)>,\n",
              " '_i23': 'import sys\\nsys.path',\n",
              " 'sys': <module 'sys' (built-in)>,\n",
              " '_23': ['/content',\n",
              "  '/env/python',\n",
              "  '/usr/lib/python310.zip',\n",
              "  '/usr/lib/python3.10',\n",
              "  '/usr/lib/python3.10/lib-dynload',\n",
              "  '',\n",
              "  '/usr/local/lib/python3.10/dist-packages',\n",
              "  '/usr/lib/python3/dist-packages',\n",
              "  '/usr/local/lib/python3.10/dist-packages/IPython/extensions',\n",
              "  '/usr/local/lib/python3.10/dist-packages/setuptools/_vendor',\n",
              "  '/root/.ipython'],\n",
              " '_i24': 'open(\"modtest.py\", \"w\").write(\\n\\'\\'\\'\"\"\"modtest: our test module\"\"\"\\ndef f(x):\\n    return x\\ndef _g(x):\\n    return x\\na = 4\\n_b = 2\\n\\'\\'\\')',\n",
              " '_24': 91,\n",
              " '_i25': '%%writefile modtest.py(\\n\"\"\"modtest: our test module\"\"\"\\ndef f(x):\\n    return x\\ndef _g(x):\\n    return x\\na = 4\\n_b = 2',\n",
              " '_i26': 'from modtest import *\\nf(3)',\n",
              " 'f': <function modtest.f(x)>,\n",
              " 'a': 4,\n",
              " '_26': 3,\n",
              " '_i27': '_g(3)',\n",
              " '_i28': 'a',\n",
              " '_28': 4,\n",
              " '_i29': '_b',\n",
              " '_i30': 'import modtest\\nmodtest._b',\n",
              " 'modtest': <module 'modtest' from '/content/modtest.py'>,\n",
              " '_30': 2,\n",
              " '_i31': 'from modtest import _g\\n_g(5)',\n",
              " '_g': <function modtest._g(x)>,\n",
              " '_31': 5,\n",
              " '_i32': 'math.ceil(3.4)',\n",
              " '_i33': 'import math\\nmath.ceil(3.4)',\n",
              " 'math': <module 'math' (built-in)>,\n",
              " '_33': 4,\n",
              " '_i34': 'del z, math, cos',\n",
              " '_i35': 'math.ceil(3.4)',\n",
              " '_35': 4,\n",
              " '_i36': 'z = 2\\nimport math\\nfrom cmath import cos\\nglobals()',\n",
              " 'z': 2,\n",
              " 'cos': <function cmath.cos(z, /)>}"
            ]
          },
          "metadata": {},
          "execution_count": 36
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "iYLPjsGAQIHk",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "efef0cb7-ba3b-421b-a22c-7acc9e4f884e"
      },
      "source": [
        "locals()"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "{'__name__': '__main__',\n",
              " '__doc__': 'Automatically created module for IPython interactive environment',\n",
              " '__package__': None,\n",
              " '__loader__': None,\n",
              " '__spec__': None,\n",
              " '__builtin__': <module 'builtins' (built-in)>,\n",
              " '__builtins__': <module 'builtins' (built-in)>,\n",
              " '_ih': ['',\n",
              "  'open(\"mymath.py\", \"w\").write(\\n\\'\\'\\'\"\"\"mymath - our example math module\"\"\"\\npi = 3.14159\\ndef area(r):\\n    \"\"\"area(r): return the area of a circle with radius r.\"\"\"\\n    return(pi * r * r) \\n\\'\\'\\')',\n",
              "  'import mymath\\npi',\n",
              "  'mymath.pi',\n",
              "  'mymath.area(2)',\n",
              "  'mymath.pi',\n",
              "  'mymath.area(2)',\n",
              "  'mymath.__doc__',\n",
              "  'mymath.area.__doc__',\n",
              "  'from mymath import pi\\npi',\n",
              "  'area(2)',\n",
              "  'import mymath, importlib\\nimportlib.reload(mymath)',\n",
              "  'import sys\\nsys.path',\n",
              "  'open(\"modtest.py\", \"w\").write(\\n\\'\\'\\'\"\"\"modtest: our test module\"\"\"\\ndef f(x):\\n    return x\\ndef _g(x):\\n    return x\\na = 4\\n_b = 2\\n\\'\\'\\')',\n",
              "  'from modtest import *\\nf(3)',\n",
              "  '_g(3)',\n",
              "  'a',\n",
              "  '_b',\n",
              "  'import modtest\\nmodtest._b',\n",
              "  'from modtest import _g\\n_g(5)',\n",
              "  'locals()',\n",
              "  'globals()',\n",
              "  'z = 2\\nimport math\\nfrom cmath import cos\\nglobals()',\n",
              "  'locals()'],\n",
              " '_oh': {1: 151,\n",
              "  3: 3.14159,\n",
              "  4: 12.56636,\n",
              "  5: 3.14159,\n",
              "  6: 12.56636,\n",
              "  7: 'mymath - our example math module',\n",
              "  8: 'area(r): return the area of a circle with radius r.',\n",
              "  9: 3.14159,\n",
              "  11: <module 'mymath' from '/content/mymath.py'>,\n",
              "  12: ['/content',\n",
              "   '/env/python',\n",
              "   '/usr/lib/python310.zip',\n",
              "   '/usr/lib/python3.10',\n",
              "   '/usr/lib/python3.10/lib-dynload',\n",
              "   '',\n",
              "   '/usr/local/lib/python3.10/dist-packages',\n",
              "   '/usr/lib/python3/dist-packages',\n",
              "   '/usr/local/lib/python3.10/dist-packages/IPython/extensions',\n",
              "   '/root/.ipython'],\n",
              "  13: 91,\n",
              "  14: 3,\n",
              "  16: 4,\n",
              "  18: 2,\n",
              "  19: 5,\n",
              "  20: {...},\n",
              "  21: {...},\n",
              "  22: {...}},\n",
              " '_dh': ['/content'],\n",
              " 'In': ['',\n",
              "  'open(\"mymath.py\", \"w\").write(\\n\\'\\'\\'\"\"\"mymath - our example math module\"\"\"\\npi = 3.14159\\ndef area(r):\\n    \"\"\"area(r): return the area of a circle with radius r.\"\"\"\\n    return(pi * r * r) \\n\\'\\'\\')',\n",
              "  'import mymath\\npi',\n",
              "  'mymath.pi',\n",
              "  'mymath.area(2)',\n",
              "  'mymath.pi',\n",
              "  'mymath.area(2)',\n",
              "  'mymath.__doc__',\n",
              "  'mymath.area.__doc__',\n",
              "  'from mymath import pi\\npi',\n",
              "  'area(2)',\n",
              "  'import mymath, importlib\\nimportlib.reload(mymath)',\n",
              "  'import sys\\nsys.path',\n",
              "  'open(\"modtest.py\", \"w\").write(\\n\\'\\'\\'\"\"\"modtest: our test module\"\"\"\\ndef f(x):\\n    return x\\ndef _g(x):\\n    return x\\na = 4\\n_b = 2\\n\\'\\'\\')',\n",
              "  'from modtest import *\\nf(3)',\n",
              "  '_g(3)',\n",
              "  'a',\n",
              "  '_b',\n",
              "  'import modtest\\nmodtest._b',\n",
              "  'from modtest import _g\\n_g(5)',\n",
              "  'locals()',\n",
              "  'globals()',\n",
              "  'z = 2\\nimport math\\nfrom cmath import cos\\nglobals()',\n",
              "  'locals()'],\n",
              " 'Out': {1: 151,\n",
              "  3: 3.14159,\n",
              "  4: 12.56636,\n",
              "  5: 3.14159,\n",
              "  6: 12.56636,\n",
              "  7: 'mymath - our example math module',\n",
              "  8: 'area(r): return the area of a circle with radius r.',\n",
              "  9: 3.14159,\n",
              "  11: <module 'mymath' from '/content/mymath.py'>,\n",
              "  12: ['/content',\n",
              "   '/env/python',\n",
              "   '/usr/lib/python310.zip',\n",
              "   '/usr/lib/python3.10',\n",
              "   '/usr/lib/python3.10/lib-dynload',\n",
              "   '',\n",
              "   '/usr/local/lib/python3.10/dist-packages',\n",
              "   '/usr/lib/python3/dist-packages',\n",
              "   '/usr/local/lib/python3.10/dist-packages/IPython/extensions',\n",
              "   '/root/.ipython'],\n",
              "  13: 91,\n",
              "  14: 3,\n",
              "  16: 4,\n",
              "  18: 2,\n",
              "  19: 5,\n",
              "  20: {...},\n",
              "  21: {...},\n",
              "  22: {...}},\n",
              " 'get_ipython': <bound method InteractiveShell.get_ipython of <google.colab._shell.Shell object at 0x79621d7d78b0>>,\n",
              " 'exit': <IPython.core.autocall.ZMQExitAutocall at 0x79621d7d7e50>,\n",
              " 'quit': <IPython.core.autocall.ZMQExitAutocall at 0x79621d7d7e50>,\n",
              " '_': {...},\n",
              " '__': {...},\n",
              " '___': {...},\n",
              " '_i': 'z = 2\\nimport math\\nfrom cmath import cos\\nglobals()',\n",
              " '_ii': 'globals()',\n",
              " '_iii': 'locals()',\n",
              " '_i1': 'open(\"mymath.py\", \"w\").write(\\n\\'\\'\\'\"\"\"mymath - our example math module\"\"\"\\npi = 3.14159\\ndef area(r):\\n    \"\"\"area(r): return the area of a circle with radius r.\"\"\"\\n    return(pi * r * r) \\n\\'\\'\\')',\n",
              " '_1': 151,\n",
              " '_i2': 'import mymath\\npi',\n",
              " 'mymath': <module 'mymath' from '/content/mymath.py'>,\n",
              " '_i3': 'mymath.pi',\n",
              " '_3': 3.14159,\n",
              " '_i4': 'mymath.area(2)',\n",
              " '_4': 12.56636,\n",
              " '_i5': 'mymath.pi',\n",
              " '_5': 3.14159,\n",
              " '_i6': 'mymath.area(2)',\n",
              " '_6': 12.56636,\n",
              " '_i7': 'mymath.__doc__',\n",
              " '_7': 'mymath - our example math module',\n",
              " '_i8': 'mymath.area.__doc__',\n",
              " '_8': 'area(r): return the area of a circle with radius r.',\n",
              " '_i9': 'from mymath import pi\\npi',\n",
              " 'pi': 3.14159,\n",
              " '_9': 3.14159,\n",
              " '_i10': 'area(2)',\n",
              " '_i11': 'import mymath, importlib\\nimportlib.reload(mymath)',\n",
              " 'importlib': <module 'importlib' from '/usr/lib/python3.10/importlib/__init__.py'>,\n",
              " '_11': <module 'mymath' from '/content/mymath.py'>,\n",
              " '_i12': 'import sys\\nsys.path',\n",
              " 'sys': <module 'sys' (built-in)>,\n",
              " '_12': ['/content',\n",
              "  '/env/python',\n",
              "  '/usr/lib/python310.zip',\n",
              "  '/usr/lib/python3.10',\n",
              "  '/usr/lib/python3.10/lib-dynload',\n",
              "  '',\n",
              "  '/usr/local/lib/python3.10/dist-packages',\n",
              "  '/usr/lib/python3/dist-packages',\n",
              "  '/usr/local/lib/python3.10/dist-packages/IPython/extensions',\n",
              "  '/root/.ipython'],\n",
              " '_i13': 'open(\"modtest.py\", \"w\").write(\\n\\'\\'\\'\"\"\"modtest: our test module\"\"\"\\ndef f(x):\\n    return x\\ndef _g(x):\\n    return x\\na = 4\\n_b = 2\\n\\'\\'\\')',\n",
              " '_13': 91,\n",
              " '_i14': 'from modtest import *\\nf(3)',\n",
              " 'f': <function modtest.f(x)>,\n",
              " 'a': 4,\n",
              " '_14': 3,\n",
              " '_i15': '_g(3)',\n",
              " '_i16': 'a',\n",
              " '_16': 4,\n",
              " '_i17': '_b',\n",
              " '_i18': 'import modtest\\nmodtest._b',\n",
              " 'modtest': <module 'modtest' from '/content/modtest.py'>,\n",
              " '_18': 2,\n",
              " '_i19': 'from modtest import _g\\n_g(5)',\n",
              " '_g': <function modtest._g(x)>,\n",
              " '_19': 5,\n",
              " '_i20': 'locals()',\n",
              " '_20': {...},\n",
              " '_i21': 'globals()',\n",
              " '_21': {...},\n",
              " '_i22': 'z = 2\\nimport math\\nfrom cmath import cos\\nglobals()',\n",
              " 'z': 2,\n",
              " 'math': <module 'math' (built-in)>,\n",
              " 'cos': <function cmath.cos(z, /)>,\n",
              " '_22': {...},\n",
              " '_i23': 'locals()'}"
            ]
          },
          "metadata": {},
          "execution_count": 23
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "cm38XPl5QIHk",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "c6c08858-5331-461c-e8aa-54f59ae9059a"
      },
      "source": [
        "math.ceil(3.4)"
      ],
      "execution_count": 37,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "4"
            ]
          },
          "metadata": {},
          "execution_count": 37
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "_gQZTN5hQIHk"
      },
      "source": [
        "del z, math, cos"
      ],
      "execution_count": 38,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "ZHr8-BzIQIHl",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 141
        },
        "outputId": "f5d9f410-b3b2-4847-f6cf-6c6e536590e3"
      },
      "source": [
        "math.ceil(3.4)"
      ],
      "execution_count": 39,
      "outputs": [
        {
          "output_type": "error",
          "ename": "NameError",
          "evalue": "name 'math' is not defined",
          "traceback": [
            "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
            "\u001b[0;31mNameError\u001b[0m                                 Traceback (most recent call last)",
            "\u001b[0;32m<ipython-input-39-307799385d47>\u001b[0m in \u001b[0;36m<cell line: 1>\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mmath\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mceil\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m3.4\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
            "\u001b[0;31mNameError\u001b[0m: name 'math' is not defined"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "i_H9_JVdQIHl",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "2a20a276-96ac-4351-eeaa-26f19080baa7"
      },
      "source": [
        "import math\n",
        "math.ceil(3.4)"
      ],
      "execution_count": 40,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "4"
            ]
          },
          "metadata": {},
          "execution_count": 40
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "DWAbTbPVQIHl",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "47d2eeb4-dfe9-433d-cced-21cc4591ab13"
      },
      "source": [
        "def f(x):\n",
        "\n",
        "    print(\"Entry local: \", locals())\n",
        "    y = x\n",
        "    print(\"Exit local: \", locals())\n",
        "\n",
        "z = 2\n",
        "\n",
        "f(z)"
      ],
      "execution_count": 41,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Entry local:  {'x': 2}\n",
            "Exit local:  {'x': 2, 'y': 2}\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "gFxCAmTwQIHm",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "66a7be1d-4e7a-4349-e9e5-18741edf4167"
      },
      "source": [
        "%%writefile scopetest.py\n",
        "\"\"\"scopetest: our scope test module\"\"\"\n",
        "v = 6\n",
        "def f(x):\n",
        "    \"\"\"f: scope test function\"\"\"\n",
        "    print(\"global: \", list(globals().keys()))\n",
        "    print(\"entry local:\", locals())\n",
        "    y = x\n",
        "    w = v\n",
        "    print(\"exit local:\", locals().keys())"
      ],
      "execution_count": 42,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Writing scopetest.py\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "WB_d6K01QIHm",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "4c0c94dd-1b73-4a37-82f0-332ac7879de6"
      },
      "source": [
        "import scopetest\n",
        "z = 2\n",
        "scopetest.f(z)"
      ],
      "execution_count": 43,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "global:  ['__name__', '__doc__', '__package__', '__loader__', '__spec__', '__file__', '__cached__', '__builtins__', 'v', 'f']\n",
            "entry local: {'x': 2}\n",
            "exit local: dict_keys(['x', 'y', 'w'])\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "## 10.7.1 The built-in namespace"
      ],
      "metadata": {
        "id": "ePnTfnWEsAkj"
      }
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "941ncuwjQIHm",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "b74c45df-5f5b-42b8-c615-ffa4dbb7e696"
      },
      "source": [
        "dir(__builtins__)"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "['ArithmeticError',\n",
              " 'AssertionError',\n",
              " 'AttributeError',\n",
              " 'BaseException',\n",
              " 'BlockingIOError',\n",
              " 'BrokenPipeError',\n",
              " 'BufferError',\n",
              " 'BytesWarning',\n",
              " 'ChildProcessError',\n",
              " 'ConnectionAbortedError',\n",
              " 'ConnectionError',\n",
              " 'ConnectionRefusedError',\n",
              " 'ConnectionResetError',\n",
              " 'DeprecationWarning',\n",
              " 'EOFError',\n",
              " 'Ellipsis',\n",
              " 'EncodingWarning',\n",
              " 'EnvironmentError',\n",
              " 'Exception',\n",
              " 'False',\n",
              " 'FileExistsError',\n",
              " 'FileNotFoundError',\n",
              " 'FloatingPointError',\n",
              " 'FutureWarning',\n",
              " 'GeneratorExit',\n",
              " 'IOError',\n",
              " 'ImportError',\n",
              " 'ImportWarning',\n",
              " 'IndentationError',\n",
              " 'IndexError',\n",
              " 'InterruptedError',\n",
              " 'IsADirectoryError',\n",
              " 'KeyError',\n",
              " 'KeyboardInterrupt',\n",
              " 'LookupError',\n",
              " 'MemoryError',\n",
              " 'ModuleNotFoundError',\n",
              " 'NameError',\n",
              " 'None',\n",
              " 'NotADirectoryError',\n",
              " 'NotImplemented',\n",
              " 'NotImplementedError',\n",
              " 'OSError',\n",
              " 'OverflowError',\n",
              " 'PendingDeprecationWarning',\n",
              " 'PermissionError',\n",
              " 'ProcessLookupError',\n",
              " 'RecursionError',\n",
              " 'ReferenceError',\n",
              " 'ResourceWarning',\n",
              " 'RuntimeError',\n",
              " 'RuntimeWarning',\n",
              " 'StopAsyncIteration',\n",
              " 'StopIteration',\n",
              " 'SyntaxError',\n",
              " 'SyntaxWarning',\n",
              " 'SystemError',\n",
              " 'SystemExit',\n",
              " 'TabError',\n",
              " 'TimeoutError',\n",
              " 'True',\n",
              " 'TypeError',\n",
              " 'UnboundLocalError',\n",
              " 'UnicodeDecodeError',\n",
              " 'UnicodeEncodeError',\n",
              " 'UnicodeError',\n",
              " 'UnicodeTranslateError',\n",
              " 'UnicodeWarning',\n",
              " 'UserWarning',\n",
              " 'ValueError',\n",
              " 'Warning',\n",
              " 'ZeroDivisionError',\n",
              " '__IPYTHON__',\n",
              " '__build_class__',\n",
              " '__debug__',\n",
              " '__doc__',\n",
              " '__import__',\n",
              " '__loader__',\n",
              " '__name__',\n",
              " '__package__',\n",
              " '__spec__',\n",
              " 'abs',\n",
              " 'aiter',\n",
              " 'all',\n",
              " 'anext',\n",
              " 'any',\n",
              " 'ascii',\n",
              " 'bin',\n",
              " 'bool',\n",
              " 'breakpoint',\n",
              " 'bytearray',\n",
              " 'bytes',\n",
              " 'callable',\n",
              " 'chr',\n",
              " 'classmethod',\n",
              " 'compile',\n",
              " 'complex',\n",
              " 'copyright',\n",
              " 'credits',\n",
              " 'delattr',\n",
              " 'dict',\n",
              " 'dir',\n",
              " 'display',\n",
              " 'divmod',\n",
              " 'enumerate',\n",
              " 'eval',\n",
              " 'exec',\n",
              " 'execfile',\n",
              " 'filter',\n",
              " 'float',\n",
              " 'format',\n",
              " 'frozenset',\n",
              " 'get_ipython',\n",
              " 'getattr',\n",
              " 'globals',\n",
              " 'hasattr',\n",
              " 'hash',\n",
              " 'help',\n",
              " 'hex',\n",
              " 'id',\n",
              " 'input',\n",
              " 'int',\n",
              " 'isinstance',\n",
              " 'issubclass',\n",
              " 'iter',\n",
              " 'len',\n",
              " 'license',\n",
              " 'list',\n",
              " 'locals',\n",
              " 'map',\n",
              " 'max',\n",
              " 'memoryview',\n",
              " 'min',\n",
              " 'next',\n",
              " 'object',\n",
              " 'oct',\n",
              " 'open',\n",
              " 'ord',\n",
              " 'pow',\n",
              " 'print',\n",
              " 'property',\n",
              " 'range',\n",
              " 'repr',\n",
              " 'reversed',\n",
              " 'round',\n",
              " 'runfile',\n",
              " 'set',\n",
              " 'setattr',\n",
              " 'slice',\n",
              " 'sorted',\n",
              " 'staticmethod',\n",
              " 'str',\n",
              " 'sum',\n",
              " 'super',\n",
              " 'tuple',\n",
              " 'type',\n",
              " 'vars',\n",
              " 'zip']"
            ]
          },
          "metadata": {},
          "execution_count": 6
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "uokKe7WYQIHn",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "96173d53-6e7d-4171-d3f6-d0b1d7ff2944"
      },
      "source": [
        "print(max.__doc__)"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "max(iterable, *[, default=obj, key=func]) -> value\n",
            "max(arg1, arg2, *args, *[, key=func]) -> value\n",
            "\n",
            "With a single iterable argument, return its biggest item. The\n",
            "default keyword-only argument specifies an object to return if\n",
            "the provided iterable is empty.\n",
            "With two or more arguments, return the largest argument.\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "p4qJLAQbQIHn",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 141
        },
        "outputId": "0333eed1-ba8e-461d-fe31-878ea8aad053"
      },
      "source": [
        "list(\"Peyto Lake\")"
      ],
      "execution_count": 48,
      "outputs": [
        {
          "output_type": "error",
          "ename": "TypeError",
          "evalue": "'list' object is not callable",
          "traceback": [
            "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
            "\u001b[0;31mTypeError\u001b[0m                                 Traceback (most recent call last)",
            "\u001b[0;32m<ipython-input-48-40590250e697>\u001b[0m in \u001b[0;36m<cell line: 1>\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mlist\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"Peyto Lake\"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
            "\u001b[0;31mTypeError\u001b[0m: 'list' object is not callable"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "iiQ3vjM_QIHn",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 159
        },
        "outputId": "be3642dd-5b57-4e4e-e349-8c75a421c51c"
      },
      "source": [
        "list = [1, 3, 5, 7]\n",
        "list(\"Peyto Lake\")"
      ],
      "execution_count": 49,
      "outputs": [
        {
          "output_type": "error",
          "ename": "TypeError",
          "evalue": "'list' object is not callable",
          "traceback": [
            "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
            "\u001b[0;31mTypeError\u001b[0m                                 Traceback (most recent call last)",
            "\u001b[0;32m<ipython-input-49-7845f2807d9f>\u001b[0m in \u001b[0;36m<cell line: 2>\u001b[0;34m()\u001b[0m\n\u001b[1;32m      1\u001b[0m \u001b[0mlist\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m[\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m3\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m5\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m7\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0mlist\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"Peyto Lake\"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
            "\u001b[0;31mTypeError\u001b[0m: 'list' object is not callable"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "pv4tIvVMQIHn",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 176
        },
        "outputId": "38931d63-3b5b-4482-f34c-9b9481cd02ac"
      },
      "source": [
        "import mymath\n",
        "mymath = mymath.area\n",
        "mymath.pi"
      ],
      "execution_count": 50,
      "outputs": [
        {
          "output_type": "error",
          "ename": "AttributeError",
          "evalue": "'function' object has no attribute 'pi'",
          "traceback": [
            "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
            "\u001b[0;31mAttributeError\u001b[0m                            Traceback (most recent call last)",
            "\u001b[0;32m<ipython-input-50-4e7325de62ae>\u001b[0m in \u001b[0;36m<cell line: 3>\u001b[0;34m()\u001b[0m\n\u001b[1;32m      1\u001b[0m \u001b[0;32mimport\u001b[0m \u001b[0mmymath\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m      2\u001b[0m \u001b[0mmymath\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mmymath\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0marea\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 3\u001b[0;31m \u001b[0mmymath\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mpi\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
            "\u001b[0;31mAttributeError\u001b[0m: 'function' object has no attribute 'pi'"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "OeTpicFdQIHo",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "3ac12935-04e3-4207-c070-1060dc233327"
      },
      "source": [
        "del list\n",
        "list(\"Peyto Lake\")"
      ],
      "execution_count": 51,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "['P', 'e', 'y', 't', 'o', ' ', 'L', 'a', 'k', 'e']"
            ]
          },
          "metadata": {},
          "execution_count": 51
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "-iF8TyyGQIHo",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "b9bc4f98-6d3e-4898-8793-fa6829e8c2a8"
      },
      "source": [
        "import mymath\n",
        "mymath.pi"
      ],
      "execution_count": 52,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "3.14159"
            ]
          },
          "metadata": {},
          "execution_count": 52
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "IHuiCFjlQIHo",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "67e1ab82-37c3-42a5-ba88-6c40c1a2a439"
      },
      "source": [
        "x1 = 6\n",
        "xl = x1 - 2\n",
        "x1"
      ],
      "execution_count": 53,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "6"
            ]
          },
          "metadata": {},
          "execution_count": 53
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "X8N9Ef5CQIH0",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "eda51fc1-111a-4e62-c9a2-71e0c98bdf90"
      },
      "source": [
        "dir()"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "['In',\n",
              " 'Out',\n",
              " '_',\n",
              " '_1',\n",
              " '_10',\n",
              " '_12',\n",
              " '_13',\n",
              " '_14',\n",
              " '_6',\n",
              " '__',\n",
              " '___',\n",
              " '__builtin__',\n",
              " '__builtins__',\n",
              " '__doc__',\n",
              " '__loader__',\n",
              " '__name__',\n",
              " '__package__',\n",
              " '__spec__',\n",
              " '_dh',\n",
              " '_i',\n",
              " '_i1',\n",
              " '_i10',\n",
              " '_i11',\n",
              " '_i12',\n",
              " '_i13',\n",
              " '_i14',\n",
              " '_i15',\n",
              " '_i2',\n",
              " '_i3',\n",
              " '_i4',\n",
              " '_i5',\n",
              " '_i6',\n",
              " '_i7',\n",
              " '_i8',\n",
              " '_i9',\n",
              " '_ih',\n",
              " '_ii',\n",
              " '_iii',\n",
              " '_oh',\n",
              " 'exit',\n",
              " 'f',\n",
              " 'get_ipython',\n",
              " 'mymath',\n",
              " 'quit',\n",
              " 'x1',\n",
              " 'xl',\n",
              " 'z']"
            ]
          },
          "metadata": {},
          "execution_count": 15
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "### Quick Check: Namespaces and scope\n",
        "Consider a variable width that's in the module `make_window.py`. In which of the following contexts is width in scope?:\n",
        "\n",
        " 1. within the module itself\n",
        " 2. inside the `resize()` function in the module\n",
        " 3. within the script that imported the `make_window.py` module\n",
        "\n",
        " **A and B but not C**"
      ],
      "metadata": {
        "id": "M6fLXJSnXqVD"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Lab 10: Create a module\n",
        "Package the functions created at the end of chapter 9 as a standalone module. Although you can include code to run the module as the main program, the goal should be for the functions to be completely usable from another script. To test, create a new Jupyter notebook and write the code to load and use the module to get the same results as the code in Chapter 9."
      ],
      "metadata": {
        "id": "wfOT4BQhYLEf"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "!wget https://raw.githubusercontent.com/nceder/qpb4e/main/code/Chapter%2006/moby_01.txt &> null  && echo Downloaded"
      ],
      "metadata": {
        "id": "Wp2veTKTp2Nj",
        "outputId": "83730322-95d6-4e14-932c-0138eae06304",
        "colab": {
          "base_uri": "https://localhost:8080/"
        }
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Downloaded\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "with open(\"text_processing_author.py\", \"w\") as f:\n",
        "    f.write(r'''\n",
        "# Author's version\n",
        "import string\n",
        "punct = str.maketrans('', '', string.punctuation)\n",
        "\n",
        "def clean_line(line):\n",
        "    \"\"\"changes case and removes punctuation\"\"\"\n",
        "    # make all one case\n",
        "    cleaned_line = line.lower()\n",
        "\n",
        "    # remove punctuation\n",
        "    cleaned_line = cleaned_line.translate(punct)\n",
        "    return cleaned_line\n",
        "\n",
        "\n",
        "def get_words(line):\n",
        "    \"\"\"splits line into words, and rejoins with newlines\"\"\"\n",
        "    words = line.split()\n",
        "    return \"\\n\".join(words) + \"\\n\"\n",
        "\n",
        "\n",
        "def count_words(words):\n",
        "    \"\"\"takes list of cleaned words, returns count dictionary\"\"\"\n",
        "    word_count = {}\n",
        "    for word in words:\n",
        "        count = word_count.setdefault(word, 0)\n",
        "        word_count[word] += 1\n",
        "    return word_count\n",
        "\n",
        "\n",
        "def word_stats(word_count):\n",
        "    \"\"\"Takes word count dictionary and returns top and bottom five entries\"\"\"\n",
        "    word_list = list(word_count.items())\n",
        "    word_list.sort(key=lambda x: x[1])\n",
        "    least_common = word_list[:5]\n",
        "    most_common = word_list[-1:-6:-1]\n",
        "    return most_common, least_common\n",
        "'''\n",
        "    )\n",
        "\n",
        "import text_processing_author\n",
        "\n",
        "\n",
        "with open(\"moby_01.txt\") as infile, open(\"moby_01_clean.txt\", \"w\") as outfile:\n",
        "    for line in infile:\n",
        "        cleaned_line = text_processing_author.clean_line(line)\n",
        "\n",
        "        cleaned_words = text_processing_author.get_words(cleaned_line)\n",
        "\n",
        "        # write all words for line\n",
        "        outfile.write(cleaned_words)\n",
        "\n",
        "moby_words = []\n",
        "with open('moby_01_clean.txt') as infile:\n",
        "    for word in infile:\n",
        "        if word.strip():\n",
        "            moby_words.append(word.strip())\n",
        "\n",
        "\n",
        "word_count = text_processing_author.count_words(moby_words)\n",
        "\n",
        "most, least = text_processing_author.word_stats(word_count)\n",
        "print(\"Most common words:\")\n",
        "for word in most:\n",
        "    print(word)\n",
        "print(\"\\nLeast common words:\")\n",
        "for word in least:\n",
        "    print(word)"
      ],
      "metadata": {
        "id": "Q2zjjWSX02Za",
        "outputId": "37dc84c3-9e6a-4668-b28e-909ab6641b87",
        "colab": {
          "base_uri": "https://localhost:8080/"
        }
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Most common words:\n",
            "('the', 14)\n",
            "('i', 9)\n",
            "('and', 9)\n",
            "('of', 8)\n",
            "('is', 7)\n",
            "\n",
            "Least common words:\n",
            "('call', 1)\n",
            "('ishmael', 1)\n",
            "('years', 1)\n",
            "('ago', 1)\n",
            "('never', 1)\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "# refactored code from Copilot\n",
        "import string\n",
        "\n",
        "def clean_line(line):\n",
        "    # Convert the line to lowercase\n",
        "    line = line.lower()\n",
        "\n",
        "    # Remove punctuation from the line\n",
        "    line = line.translate(str.maketrans('', '', string.punctuation))\n",
        "\n",
        "    return line\n",
        "\n",
        "def write_words_to_file(words, output_file):\n",
        "    # Write each word to the output file\n",
        "    for word in words:\n",
        "        output_file.write(word + '\\n')\n",
        "\n",
        "def count_word_occurrences(words):\n",
        "    # Count the occurrences of each word using a dictionary\n",
        "    word_counts = {}\n",
        "    for word in words:\n",
        "        if word in word_counts:\n",
        "            word_counts[word] += 1\n",
        "        else:\n",
        "            word_counts[word] = 1\n",
        "\n",
        "    return word_counts\n",
        "\n",
        "def print_common_words(word_counts, n):\n",
        "    # Sort the word counts in descending order\n",
        "    sorted_word_counts = sorted(word_counts.items(), key=lambda x: x[1], reverse=True)\n",
        "\n",
        "    # Print the n most common words and their occurrences\n",
        "    print(f\"{n} most common words:\")\n",
        "    for word, count in sorted_word_counts[:n]:\n",
        "        print(f\"{word}: {count}\")\n",
        "\n",
        "def print_least_common_words(word_counts, n):\n",
        "    # Sort the word counts in descending order\n",
        "    sorted_word_counts = sorted(word_counts.items(), key=lambda x: x[1], reverse=True)\n",
        "\n",
        "    # Print the n least common words and their occurrences\n",
        "    print(f\"{n} least common words:\")\n",
        "    for word, count in sorted_word_counts[-n:]:\n",
        "        print(f\"{word}: {count}\")\n",
        "\n",
        "def process_file(input_file_path, output_file_path):\n",
        "    # Open the input file for reading\n",
        "    with open(input_file_path, 'r') as input_file:\n",
        "        # Open the output file for writing\n",
        "        with open(output_file_path, 'w') as output_file:\n",
        "            # Iterate over each line in the input file\n",
        "            for line in input_file:\n",
        "                # Clean the line\n",
        "                cleaned_line = clean_line(line)\n",
        "\n",
        "                # Split the line into words\n",
        "                words = cleaned_line.split()\n",
        "\n",
        "                # Write the words to the output file\n",
        "                write_words_to_file(words, output_file)\n",
        "\n",
        "def main():\n",
        "    input_file_path = 'moby_01.txt'\n",
        "    output_file_path = 'moby_01_clean.txt'\n",
        "\n",
        "    # Process the file\n",
        "    process_file(input_file_path, output_file_path)\n",
        "\n",
        "    # Open the file\n",
        "    with open(output_file_path, 'r') as file:\n",
        "        # Read the file content\n",
        "        content = file.read()\n",
        "\n",
        "    # Split the content into words\n",
        "    words = content.split()\n",
        "\n",
        "    # Count word occurrences\n",
        "    word_counts = count_word_occurrences(words)\n",
        "\n",
        "    # Print the five most common words and their occurrences\n",
        "    print_common_words(word_counts, 5)\n",
        "\n",
        "    # Print the five least common words and their occurrences\n",
        "    print_least_common_words(word_counts, 5)\n",
        "\n",
        "if __name__ == \"__main__\":\n",
        "    main()"
      ],
      "metadata": {
        "id": "8fX3Mk7CXklB",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "775361a5-9f56-4543-f229-61921a31d823"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "5 most common words:\n",
            "the: 14\n",
            "and: 9\n",
            "i: 9\n",
            "of: 8\n",
            "is: 7\n",
            "5 least common words:\n",
            "land: 1\n",
            "look: 1\n",
            "at: 1\n",
            "crowds: 1\n",
            "watergazers: 1\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "# Generated by colaboratory\n",
        "# prompt: Package the functions in the cell above as a standalone module so that\n",
        "#         the module can be used by other code. Then write the code to use the\n",
        "#         module to achieve the same result as the cell above.\n",
        "\n",
        "# Save the functions as a module named \"text_processing.py\"\n",
        "with open(\"text_processing.py\", \"w\") as f:\n",
        "    f.write(r\"\"\"\n",
        "def clean_line(line):\n",
        "    # Convert the line to lowercase\n",
        "    line = line.lower()\n",
        "\n",
        "    # Remove punctuation from the line\n",
        "    line = line.translate(str.maketrans('', '', string.punctuation))\n",
        "\n",
        "    return line\n",
        "\n",
        "def write_words_to_file(words, output_file):\n",
        "    # Write each word to the output file\n",
        "    for word in words:\n",
        "        output_file.write(word + '\\n')\n",
        "\n",
        "def count_word_occurrences(words):\n",
        "    # Count the occurrences of each word using a dictionary\n",
        "    word_counts = {}\n",
        "    for word in words:\n",
        "        if word in word_counts:\n",
        "            word_counts[word] += 1\n",
        "        else:\n",
        "            word_counts[word] = 1\n",
        "\n",
        "    return word_counts\n",
        "\n",
        "def print_common_words(word_counts, n):\n",
        "    # Sort the word counts in descending order\n",
        "    sorted_word_counts = sorted(word_counts.items(), key=lambda x: x[1], reverse=True)\n",
        "\n",
        "    # Print the n most common words and their occurrences\n",
        "    print(f\"{n} most common words:\")\n",
        "    for word, count in sorted_word_counts[:n]:\n",
        "        print(f\"{word}: {count}\")\n",
        "\n",
        "def print_least_common_words(word_counts, n):\n",
        "    # Sort the word counts in descending order\n",
        "    sorted_word_counts = sorted(word_counts.items(), key=lambda x: x[1], reverse=True)\n",
        "\n",
        "    # Print the n least common words and their occurrences\n",
        "    print(f\"{n} least common words:\")\n",
        "    for word, count in sorted_word_counts[-n:]:\n",
        "        print(f\"{word}: {count}\")\n",
        "\n",
        "def process_file(input_file_path, output_file_path):\n",
        "    # Open the input file for reading\n",
        "    with open(input_file_path, 'r') as input_file:\n",
        "        # Open the output file for writing\n",
        "        with open(output_file_path, 'w') as output_file:\n",
        "            # Iterate over each line in the input file\n",
        "            for line in input_file:\n",
        "                # Clean the line\n",
        "                cleaned_line = clean_line(line)\n",
        "\n",
        "                # Split the line into words\n",
        "                words = cleaned_line.split()\n",
        "\n",
        "                # Write the words to the output file\n",
        "                write_words_to_file(words, output_file)\n",
        "\"\"\")\n",
        "\n",
        "# Use the module\n",
        "import text_processing\n",
        "\n",
        "input_file_path = 'moby_01.txt'\n",
        "output_file_path = 'moby_01_clean.txt'\n",
        "\n",
        "# Process the file\n",
        "text_processing.process_file(input_file_path, output_file_path)\n",
        "\n",
        "# Open the file\n",
        "with open(output_file_path, 'r') as file:\n",
        "    # Read the file content\n",
        "    content = file.read()\n",
        "\n",
        "# Split the content into words\n",
        "words = content.split()\n",
        "\n",
        "# Count word occurrences\n",
        "word_counts = text_processing.count_word_occurrences(words)\n",
        "\n",
        "# Print the five most common words and their occurrences\n",
        "text_processing.print_common_words(word_counts, 5)\n",
        "\n",
        "# Print the five least common words and their occurrences\n",
        "text_processing.print_least_common_words(word_counts, 5)\n"
      ],
      "metadata": {
        "id": "MT3L-QMVpQ3M",
        "outputId": "77bdc942-8e95-47d2-8366-5f21a99dfe68",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 356
        }
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "error",
          "ename": "NameError",
          "evalue": "name 'string' is not defined",
          "traceback": [
            "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
            "\u001b[0;31mNameError\u001b[0m                                 Traceback (most recent call last)",
            "\u001b[0;32m<ipython-input-2-472b2a5e47db>\u001b[0m in \u001b[0;36m<cell line: 76>\u001b[0;34m()\u001b[0m\n\u001b[1;32m     74\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m     75\u001b[0m \u001b[0;31m# Process the file\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 76\u001b[0;31m \u001b[0mtext_processing\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mprocess_file\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0minput_file_path\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0moutput_file_path\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m     77\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m     78\u001b[0m \u001b[0;31m# Open the file\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
            "\u001b[0;32m/content/text_processing.py\u001b[0m in \u001b[0;36mprocess_file\u001b[0;34m(input_file_path, output_file_path)\u001b[0m\n\u001b[1;32m     51\u001b[0m             \u001b[0;32mfor\u001b[0m \u001b[0mline\u001b[0m \u001b[0;32min\u001b[0m \u001b[0minput_file\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m     52\u001b[0m                 \u001b[0;31m# Clean the line\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 53\u001b[0;31m                 \u001b[0mcleaned_line\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mclean_line\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mline\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m     54\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m     55\u001b[0m                 \u001b[0;31m# Split the line into words\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
            "\u001b[0;32m/content/text_processing.py\u001b[0m in \u001b[0;36mclean_line\u001b[0;34m(line)\u001b[0m\n\u001b[1;32m      5\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m      6\u001b[0m     \u001b[0;31m# Remove punctuation from the line\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 7\u001b[0;31m     \u001b[0mline\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mline\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mtranslate\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mstr\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mmaketrans\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m''\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m''\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mstring\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mpunctuation\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m      8\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m      9\u001b[0m     \u001b[0;32mreturn\u001b[0m \u001b[0mline\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
            "\u001b[0;31mNameError\u001b[0m: name 'string' is not defined"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "* add r before file string (otherwise \\\\n in line 14 is written as linefeed).\n",
        "* import string in line 1 of module."
      ],
      "metadata": {
        "id": "t2oUzZAGrqwB"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "### Copilot version"
      ],
      "metadata": {
        "id": "X61DA4oGss9-"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "# Copilot version\n",
        "# FILENAME: word_processing.py\n",
        "\n",
        "import string\n",
        "\n",
        "def clean_line(line):\n",
        "    line = line.lower()\n",
        "    line = line.translate(str.maketrans('', '', string.punctuation))\n",
        "    return line\n",
        "\n",
        "def write_words_to_file(words, output_file):\n",
        "    for word in words:\n",
        "        output_file.write(word + '\\n')\n",
        "\n",
        "def count_word_occurrences(words):\n",
        "    word_counts = {}\n",
        "    for word in words:\n",
        "        if word in word_counts:\n",
        "            word_counts[word] += 1\n",
        "        else:\n",
        "            word_counts[word] = 1\n",
        "    return word_counts\n",
        "\n",
        "def print_common_words(word_counts, n):\n",
        "    sorted_word_counts = sorted(word_counts.items(), key=lambda x: x[1], reverse=True)\n",
        "    print(f\"{n} most common words:\")\n",
        "    for word, count in sorted_word_counts[:n]:\n",
        "        print(f\"{word}: {count}\")\n",
        "\n",
        "def print_least_common_words(word_counts, n):\n",
        "    sorted_word_counts = sorted(word_counts.items(), key=lambda x: x[1], reverse=True)\n",
        "    print(f\"{n} least common words:\")\n",
        "    for word, count in sorted_word_counts[-n:]:\n",
        "        print(f\"{word}: {count}\")\n",
        "\n",
        "def process_file(input_file_path, output_file_path):\n",
        "    with open(input_file_path, 'r') as input_file:\n",
        "        with open(output_file_path, 'w') as output_file:\n",
        "            for line in input_file:\n",
        "                cleaned_line = clean_line(line)\n",
        "                words = cleaned_line.split()\n",
        "                write_words_to_file(words, output_file)\n"
      ],
      "metadata": {
        "id": "S0aU1YkdszFc",
        "outputId": "5108e912-b514-443a-8dae-9cf9147f0914",
        "colab": {
          "base_uri": "https://localhost:8080/"
        }
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "1369"
            ]
          },
          "metadata": {},
          "execution_count": 5
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "# FILENAME: main.py\n",
        "\n",
        "import word_processing\n",
        "\n",
        "input_file_path = \"path_to_input_file\"\n",
        "output_file_path = \"path_to_output_file\"\n",
        "\n",
        "# Process the file\n",
        "word_processing.process_file(input_file_path, output_file_path)\n",
        "\n",
        "# Count word occurrences\n",
        "with open(output_file_path, 'r') as output_file:\n",
        "    words = output_file.read().split()\n",
        "    word_counts = word_processing.count_word_occurrences(words)\n",
        "\n",
        "# Print common and least common words\n",
        "word_processing.print_common_words(word_counts, 10)\n",
        "word_processing.print_least_common_words(word_counts, 10)"
      ],
      "metadata": {
        "id": "9sAKNNl2TZGZ",
        "outputId": "53642064-79f8-46a3-82f7-c0bc5eb69f45",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 332
        }
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "error",
          "ename": "FileNotFoundError",
          "evalue": "[Errno 2] No such file or directory: 'path_to_input_file'",
          "traceback": [
            "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
            "\u001b[0;31mFileNotFoundError\u001b[0m                         Traceback (most recent call last)",
            "\u001b[0;32m<ipython-input-6-04d8ffa3c837>\u001b[0m in \u001b[0;36m<cell line: 9>\u001b[0;34m()\u001b[0m\n\u001b[1;32m      7\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m      8\u001b[0m \u001b[0;31m# Process the file\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 9\u001b[0;31m \u001b[0mword_processing\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mprocess_file\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0minput_file_path\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0moutput_file_path\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m     10\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m     11\u001b[0m \u001b[0;31m# Count word occurrences\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
            "\u001b[0;32m/content/word_processing.py\u001b[0m in \u001b[0;36mprocess_file\u001b[0;34m(input_file_path, output_file_path)\u001b[0m\n\u001b[1;32m     35\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m     36\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mprocess_file\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0minput_file_path\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0moutput_file_path\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 37\u001b[0;31m     \u001b[0;32mwith\u001b[0m \u001b[0mopen\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0minput_file_path\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m'r'\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;32mas\u001b[0m \u001b[0minput_file\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m     38\u001b[0m         \u001b[0;32mwith\u001b[0m \u001b[0mopen\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0moutput_file_path\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m'w'\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;32mas\u001b[0m \u001b[0moutput_file\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m     39\u001b[0m             \u001b[0;32mfor\u001b[0m \u001b[0mline\u001b[0m \u001b[0;32min\u001b[0m \u001b[0minput_file\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
            "\u001b[0;31mFileNotFoundError\u001b[0m: [Errno 2] No such file or directory: 'path_to_input_file'"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "# FILENAME: main.py\n",
        "\n",
        "import word_processing\n",
        "\n",
        "input_file_path = \"moby_01.txt\"\n",
        "output_file_path = \"moby_01_clean.txt\"\n",
        "\n",
        "# Process the file\n",
        "word_processing.process_file(input_file_path, output_file_path)\n",
        "\n",
        "# Count word occurrences\n",
        "with open(output_file_path, 'r') as output_file:\n",
        "    words = output_file.read().split()\n",
        "    word_counts = word_processing.count_word_occurrences(words)\n",
        "\n",
        "# Print common and least common words\n",
        "word_processing.print_common_words(word_counts, 10)\n",
        "word_processing.print_least_common_words(word_counts, 10)"
      ],
      "metadata": {
        "id": "-Q7J_wJDVvzv",
        "outputId": "1de0901c-df56-4d86-c432-09bb7fe78281",
        "colab": {
          "base_uri": "https://localhost:8080/"
        }
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "10 most common words:\n",
            "the: 14\n",
            "and: 9\n",
            "i: 9\n",
            "of: 8\n",
            "is: 7\n",
            "a: 6\n",
            "it: 6\n",
            "me: 5\n",
            "to: 5\n",
            "in: 4\n",
            "10 least common words:\n",
            "hours: 1\n",
            "previous: 1\n",
            "were: 1\n",
            "out: 1\n",
            "sight: 1\n",
            "land: 1\n",
            "look: 1\n",
            "at: 1\n",
            "crowds: 1\n",
            "watergazers: 1\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [],
      "metadata": {
        "id": "IRiy9cv7V5L3"
      },
      "execution_count": null,
      "outputs": []
    }
  ]
}